package bx.com.smartcashier.activity;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.res.AssetFileDescriptor;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.Vibrator;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.SurfaceHolder;
import android.view.SurfaceHolder.Callback;
import android.view.SurfaceView;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.ChecksumException;
import com.google.zxing.DecodeHintType;
import com.google.zxing.FormatException;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;


import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.List;
import java.util.Map;
import java.util.Vector;
import bx.com.smartcashier.R;
import bx.com.smartcashier.config.ServerUrl;
import bx.com.smartcashier.mode.SmartShopOrderDetailVO;
import bx.com.smartcashier.mode.SmartShopOrderVO;
import bx.com.smartcashier.mode.SmartShopTradeOrderVO;
import bx.com.smartcashier.utils.JsonUtils;
import bx.com.smartcashier.view.ReturnGoodsDetailFragment;
import bx.com.smartcashier.zxing.Constants;
import bx.com.smartcashier.zxing.camera.CameraManager;
import bx.com.smartcashier.zxing.decoding.CaptureReturnGoodsActivityHandler;
import bx.com.smartcashier.zxing.decoding.InactivityTimer;
import bx.com.smartcashier.zxing.decoding.RGBLuminanceSource;
import bx.com.smartcashier.zxing.view.ViewfinderView;


/**
 * Initial the camera
 *
 * @author Ryan.Tang
 */
public class ReturnGoodsActivity extends AppCompatActivity implements Callback {

    private static final int REQUEST_CODE_SCAN_GALLERY = 100;

    private CaptureReturnGoodsActivityHandler handler;
    private ViewfinderView viewfinderView;
    private ImageButton back;
    private boolean hasSurface;
    private Vector<BarcodeFormat> decodeFormats;
    private String characterSet;
    private InactivityTimer inactivityTimer;
    private MediaPlayer mediaPlayer;
    private boolean playBeep;
    private static final float BEEP_VOLUME = 0.10f;
    private boolean vibrate;
    private ProgressDialog mProgress;
    private String photo_path;
    private Bitmap scanBitmap;
    HashSet<String> set=new HashSet<>();

    ArrayList<SmartShopOrderDetailVO> results=new ArrayList<>();
    private ListView lvResult;
    private BaseAdapter adapter;
    private String token;
    private String shopId;
    private TextView tvTotal;
    private Button btnPay;
    private BigDecimal totalPrice=new BigDecimal("0");
    private Integer parentId;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_return_goods);
        CameraManager.init(getApplication());
        viewfinderView = (ViewfinderView) findViewById(R.id.viewfinder_content);
        lvResult=findViewById(R.id.lv_result);
        tvTotal=findViewById(R.id.tv_total);
        btnPay=findViewById(R.id.btn_pay);
        hasSurface = false;
        inactivityTimer = new InactivityTimer(this);
        initDatas();
        SharedPreferences sharedPreferences = getSharedPreferences("User",0);
        token = sharedPreferences.getString("token","null");
        shopId = sharedPreferences.getString("shopId","null");
        setListenner();
        //添加toolbar
        addToolbar();
    }



    private void addToolbar() {
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);

        setSupportActionBar(toolbar);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayShowTitleEnabled(false);
//        //设置是否有返回箭头
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);


    }
    /**
     *
     */
    private void setListenner() {
        btnPay.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(results.size()!=0){
                    String goodsname="";
                    ArrayList<SmartShopOrderDetailVO> rs=new ArrayList<>();
                    for (int i = 0; i <results.size(); i++) {


                        if(results.get(i).getChecked()){
                            if(results.get(i).getGoodsName().equals(goodsname)){
                                for (int j = 0; j <rs.size() ; j++) {
                                    if(rs.get(j).getGoodsName().equals(goodsname)){
                                        rs.get(j).setBuyCount(rs.get(j).getBuyCount()+new Integer("1"));
                                    }
                                }
                            }else{
                                rs.add(results.get(i));
                            }

                        }
                        goodsname=results.get(i).getGoodsName();
                    }
                    ReturnGoodsDetailFragment payDetailFragment=new ReturnGoodsDetailFragment();
                    Bundle bundle=new Bundle();
                    bundle.putString("totalPrice",totalPrice+"");
                    bundle.putInt("parentId",parentId);
                    bundle.putParcelableArrayList("rs",rs);
                    payDetailFragment.setArguments(bundle);
                    payDetailFragment.show(getSupportFragmentManager(),"ReturnGoodsDetailFragment");

                }else{
                    Toast.makeText(ReturnGoodsActivity.this,"未扫描到商品，无法结算！",Toast.LENGTH_LONG).show();
                }
            }
        });
    }


    private void initDatas() {
        adapter=new BaseAdapter(){

            @Override
            public int getCount() {
                return results.size();
            }

            @Override
            public SmartShopOrderDetailVO getItem(int position) {
                return results.get(position);
            }

            @Override
            public long getItemId(int position) {
                return position;
            }

            @Override
            public View getView(int position, View convertView, ViewGroup parent) {
                final SmartShopOrderDetailVO one = getItem(position);
                View view;
                ViewHolder viewHolder;

                if (convertView == null){
                    // inflate出子项布局，实例化其中的图片控件和文本控件
                    view = LayoutInflater.from(ReturnGoodsActivity.this).inflate(R.layout.return_goods_item, null);

                    viewHolder = new ViewHolder();
                    // 通过id得到图片控件实例
                    viewHolder.goodsDetail = (TextView) view.findViewById(R.id.tv_goods_detail);
                    // 通过id得到文本空间实例
                    viewHolder.price = (TextView) view.findViewById(R.id.tv_goods_price);
                    viewHolder.cb= (ImageView)view.findViewById(R.id.cb_chose);
                    // 缓存图片控件和文本控件的实例
                    view.setTag(viewHolder);
                }else{
                    view = convertView;
                    // 取出缓存
                    viewHolder = (ViewHolder) view.getTag();
                }

                viewHolder.goodsDetail.setText(one.getGoodsName());
                // 文本控件设置文本内容
                viewHolder.price.setText("￥"+one.getRetailPrice());

                viewHolder.cb.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        results.remove(one);
                        set.remove(one.getMycode());
                        notifyDataSetChanged();
                        handler.restartPreviewAndDecode();
                        jsPrice();
                    }
                });

//                viewHolder.goodsDetail.setText(one.getGoodsName());
//                // 文本控件设置文本内容
//                viewHolder.price.setText("￥"+one.getRetailPrice());
//                viewHolder.cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
//                    @Override
//                    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//                        one.setChecked(isChecked);
//                        jsPrice();
//                    }
//                });

                return view;
            }
            // 内部类
            class ViewHolder{
                TextView goodsDetail;
                TextView price;
                ImageView cb;
            }

        };
        lvResult.setAdapter(adapter);


    }



    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if(item.getItemId() == android.R.id.home){
            finish();
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    protected void onActivityResult(final int requestCode, int resultCode, Intent data) {
        if (requestCode==RESULT_OK) {
            switch (requestCode) {
                case REQUEST_CODE_SCAN_GALLERY:
                    //获取选中图片的路径
                    Cursor cursor = getContentResolver().query(data.getData(), null, null, null, null);
                    if (cursor.moveToFirst()) {
                        photo_path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
                    }
                    cursor.close();

                    mProgress = new ProgressDialog(ReturnGoodsActivity.this);
                    mProgress.setMessage("正在扫描...");
                    mProgress.setCancelable(false);
                    mProgress.show();

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            Result result = scanningImage(photo_path);
                            if (result != null) {
                                Intent resultIntent = new Intent();
                                Bundle bundle = new Bundle();
                                bundle.putString(Constants.INTENT_EXTRA_KEY_QR_SCAN ,result.getText());
                                resultIntent.putExtras(bundle);
                                ReturnGoodsActivity.this.setResult(RESULT_OK, resultIntent);

                            } else {
                                Message m = handler.obtainMessage();
                                m.what = R.id.decode_failed;
                                m.obj = "Scan failed!";
                                handler.sendMessage(m);
                            }
                        }
                    }).start();
                    break;
            }
        }
        super.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 扫描二维码图片的方法
     * @param path
     * @return
     */
    public Result scanningImage(String path) {
        if(TextUtils.isEmpty(path)){
            return null;
        }
        Hashtable<DecodeHintType, String> hints = new Hashtable<>();
        hints.put(DecodeHintType.CHARACTER_SET, "UTF8"); //设置二维码内容的编码

        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true; // 先获取原大小
        scanBitmap = BitmapFactory.decodeFile(path, options);
        options.inJustDecodeBounds = false; // 获取新的大小
        int sampleSize = (int) (options.outHeight / (float) 200);
        if (sampleSize <= 0)
            sampleSize = 1;
        options.inSampleSize = sampleSize;
        scanBitmap = BitmapFactory.decodeFile(path, options);
        RGBLuminanceSource source = new RGBLuminanceSource(scanBitmap);
        BinaryBitmap bitmap1 = new BinaryBitmap(new HybridBinarizer(source));
        QRCodeReader reader = new QRCodeReader();
        try {
            return reader.decode(bitmap1, hints);
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (ChecksumException e) {
            e.printStackTrace();
        } catch (FormatException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onResume() {
        super.onResume();
        SurfaceView surfaceView = (SurfaceView) findViewById(R.id.scanner_view);
        SurfaceHolder surfaceHolder = surfaceView.getHolder();
        if (hasSurface) {
            initCamera(surfaceHolder);
        } else {
            surfaceHolder.addCallback(this);
            surfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }
        decodeFormats = null;
        characterSet = null;

        playBeep = true;
        AudioManager audioService = (AudioManager) getSystemService(AUDIO_SERVICE);
        if (audioService.getRingerMode() != AudioManager.RINGER_MODE_NORMAL) {
            playBeep = false;
        }
        initBeepSound();
        vibrate = true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        if (handler != null) {
            handler.quitSynchronously();
            handler = null;
        }
        CameraManager.get().closeDriver();
    }

    @Override
    protected void onDestroy() {
        inactivityTimer.shutdown();
        super.onDestroy();
    }

    /**
     * Handler scan result
     *
     * @param result
     * @param barcode
     */
    public void handleDecode(Result result, Bitmap barcode) {
        inactivityTimer.onActivity();
        playBeepSoundAndVibrate();
        String resultString = result.getText();
        //FIXME
        if (TextUtils.isEmpty(resultString)) {
            Toast.makeText(ReturnGoodsActivity.this, "Scan failed!", Toast.LENGTH_SHORT).show();
        } else {

            System.out.println("sssssssssssssssss scan 0 = " + resultString);

            // 不能使用Intent传递大于40kb的bitmap，可以使用一个单例对象存储这个bitmap
//            bundle.putParcelable("bitmap", barcode);
//            Logger.d("saomiao",resultString);
//            resultIntent.putExtras(bundle);
//            this.setResult(RESULT_OK, resultIntent);

            if(set.contains(resultString)){
                Toast.makeText(this,"此商品已经扫描，请勿重新扫",Toast.LENGTH_LONG).show();
            }else{
                set.add(resultString);
//                getGoodsDetail("165001005001");
                getGoodsDetail(resultString);
            }


        }

    }

    private void getGoodsDetail(final String resultString) {

        RequestQueue requestQueue = Volley.newRequestQueue(this);

        StringRequest stringRequest = new StringRequest(Request.Method.POST,
                ServerUrl.url + "/SmartShopOrder/selectOrderByParam.json",
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String s) {
                        s = s.replace(" ","");
                        Map<String,Object> map = JsonUtils.getMap(s);
                        if(String.valueOf(map.get("code")).equals("000000"))
                        {
                            SmartShopTradeOrderVO vo = null;
                            try {
                                vo = (SmartShopTradeOrderVO) JsonUtils.toObject(String.valueOf(map.get("data")),SmartShopTradeOrderVO.class);

                                List<SmartShopOrderVO> shopOrders = vo.getSmartShopOrderVOS();
                                if(shopOrders!=null&&shopOrders.size()>0){
                                    List<SmartShopOrderDetailVO> details = shopOrders.get(0).getSmartShopOrderDetailVOS();
                                    if(details!=null&&details.size()>0){
                                        SmartShopOrderDetailVO smartShopOrderDetailVO = details.get(0);
                                        smartShopOrderDetailVO.setParentId(shopOrders.get(0).getId());
                                        smartShopOrderDetailVO.setMycode(resultString);
                                        parentId=shopOrders.get(0).getId();
                                        results.add(smartShopOrderDetailVO);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }


                            adapter.notifyDataSetChanged();
                            jsPrice();


                        }
                        else
                        {
                            Toast.makeText(ReturnGoodsActivity.this, JsonUtils.getMap(s).get("msg").toString(), Toast.LENGTH_SHORT).show();
                        }
                        handler.restartPreviewAndDecode();
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.e("111", "onErrorResponse: ", volleyError);
                Toast.makeText(ReturnGoodsActivity.this, "获取商品信息异常!", Toast.LENGTH_SHORT).show();
                handler.restartPreviewAndDecode();
            }
        })
        {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                map.put("uniqueCode",resultString);
//                map.put("uniqueCode","165001005001");
                map.put("shopId",shopId);
                map.put("status","1");
                map.put("token", token);
                return map;
            }
        };
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(60*1000,0,DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        requestQueue.add(stringRequest);

    }

    /**
     * 计算选中商品的价格
     */
    private void jsPrice() {
        totalPrice=new BigDecimal("0");
        for (int i = 0; i <results.size() ; i++) {
            if(results.get(i).getChecked())totalPrice=totalPrice.add(results.get(i).getRetailPrice());
        }
        tvTotal.setText("￥"+totalPrice);
    }

    private void initCamera(SurfaceHolder surfaceHolder) {
        try {
            CameraManager.get().openDriver(surfaceHolder);
        } catch (IOException ioe) {
            return;
        } catch (RuntimeException e) {
            return;
        }
        if (handler == null) {
            handler = new CaptureReturnGoodsActivityHandler(this, decodeFormats,
                    characterSet);
        }
    }

    @Override
    public void surfaceChanged(SurfaceHolder holder, int format, int width,
                               int height) {

    }

    @Override
    public void surfaceCreated(SurfaceHolder holder) {
        if (!hasSurface) {
            hasSurface = true;
            initCamera(holder);
        }

    }

    @Override
    public void surfaceDestroyed(SurfaceHolder holder) {
        hasSurface = false;

    }

    public ViewfinderView getViewfinderView() {
        return viewfinderView;
    }

    public Handler getHandler() {
        return handler;
    }

    public void drawViewfinder() {
        viewfinderView.drawViewfinder();

    }

    private void initBeepSound() {
        if (playBeep && mediaPlayer == null) {
            // The volume on STREAM_SYSTEM is not adjustable, and users found it
            // too loud,
            // so we now play on the music stream.
            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = new MediaPlayer();
            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
            mediaPlayer.setOnCompletionListener(beepListener);

            AssetFileDescriptor file = getResources().openRawResourceFd(
                    R.raw.beep);
            try {
                mediaPlayer.setDataSource(file.getFileDescriptor(),
                        file.getStartOffset(), file.getLength());
                file.close();
                mediaPlayer.setVolume(BEEP_VOLUME, BEEP_VOLUME);
                mediaPlayer.prepare();
            } catch (IOException e) {
                mediaPlayer = null;
            }
        }
    }

    private static final long VIBRATE_DURATION = 200L;

    private void playBeepSoundAndVibrate() {
        if (playBeep && mediaPlayer != null) {
            mediaPlayer.start();
        }
        if (vibrate) {
            Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
            vibrator.vibrate(VIBRATE_DURATION);
        }
    }

    /**
     * When the beep has finished playing, rewind to queue up another one.
     */
    private final OnCompletionListener beepListener = new OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer) {
            mediaPlayer.seekTo(0);
        }
    };

}